package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.Result;
import com.qk.common.enums.param.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public Result list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPage(), userDTO.getPageSize());
        List<UserDO> userList = userMapper.selectByPage(userDTO);
        Page<UserDO> page =(Page<UserDO>) userList;
        PageResult<UserDO>  pageResult =  PageResult.<UserDO>builder().total(Math.toIntExact(page.getTotal())).rows(page.getResult()).build();
        return Result.success(pageResult);
    }

    @Override
    public void addUser(User user) {

        Boolean result = BeanUtil.hasNullField(user,"id","password","deptId","roleId","image","remark","createTime","updateTime");
        if(result){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        user.setPassword(DigestUtils.md5DigestAsHex(new StringBuilder(user.getUsername()).append("123").toString().getBytes()));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insert(user);

    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public User getUser(Integer id) {
        return userMapper.selectUserById(id);
    }

    @Override
    public void deleteUser(List<Integer> ids) {
        userMapper.deleteUser(ids);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if(hasNull){
            CommonException.throwException(ParamEnum.PARAM_ERROR);
        }
        User dbuser = userMapper.selectUserByName(dto.getUsername());
        boolean isNull = Objects.isNull(dbuser);
        if(isNull){
            CommonException.throwException(ParamEnum.USERNAME_ERROR);
        }
        Role role = roleMapper.selectRoleById(dbuser.getRoleId());
        boolean isChecked = ObjectUtil.equal(dbuser.getPassword(), DigestUtils.md5DigestAsHex(dto.getPassword().getBytes()));
        if(!isChecked){
            CommonException.throwException(ParamEnum.PASSWORD_ERROR);
        }
        if(dbuser.getStatus() == 0){
            CommonException.throwException(ParamEnum.STATUS_ERROR);
        }
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",dbuser.getId());
        claims.put("username",dbuser.getUsername());

        return UserLoginVO.builder()
                .id(dbuser.getId())
                .username(dbuser.getUsername())
                .name(dbuser.getName())
                .image(dbuser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }

    @Override
    public List<User> selectByRoleId(String roleLabel) {
        return userMapper.selectByRoleLabel(roleLabel);
    }
}
